package com.copa.module.user.manage.impl;

import cn.hutool.core.util.ObjectUtil;
import com.copa.constant.RoleConstant;
import com.copa.domain.ResponseDto;
import com.copa.module.user.domain.dto.UserLoginDTO;
import com.copa.module.user.domain.entity.UserEntity;
import com.copa.module.user.mapper.RoleDao;
import com.copa.module.user.mapper.UserDao;
import com.copa.module.user.domain.entity.RoleEntity;
import com.copa.module.user.manage.UserRoleManage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author copa
 * @createDate 2021-01-05 14:09
 * @function
 */
@Service
public class UserRoleManageImpl implements UserRoleManage {

    @Autowired
    private RoleDao roleDao;

    @Autowired
    private UserDao userDao;

    @Override
    public ResponseDto<List<Long>> listRoleByUserIdAndRoleId(Long userId, Long roleId) {
        List<Long> roldIds = roleDao.listRoleByUserIdAndRoleId(userId, roleId);
        if (ObjectUtil.isNotNull(roldIds) && ObjectUtil.length(roldIds) > 0) {
            return ResponseDto.success(roldIds);
        }
        return ResponseDto.errorMsg("抱歉，该用户没有权限！");
    }

    @Override
    public ResponseDto<UserLoginDTO> findUserByUsernameAndPassword(Long userId) {
        UserLoginDTO userLoginDTO = new UserLoginDTO();
        ResponseDto<List<Long>> roleIdsRes = listRoleByUserIdAndRoleId(userId, RoleConstant.ADMIN.longValue());
        if (roleIdsRes.isNotSuccess()) {
            return ResponseDto.errorMsg("抱歉，该用户没有权限！");
        }
        UserEntity user = userDao.selectById(userId);
        RoleEntity role = roleDao.selectById(roleIdsRes.getData().get(0));
        userLoginDTO.setUser(user)
                .setRole(role);
        return ResponseDto.success(userLoginDTO);
    }
}
